<script setup>
	import { ref, onMounted } from 'vue'

	import axios from 'axios'
	import AddUser from './AddUser.vue'
	import { 
		get_total_records, handle_page_change, 
		handle_edit, handle_del, handle_view, 
		get_user_cards, handle_status_change, 
		get_class_records, get_consume_records,
		get_res_records } from '@/api/member.js'
	const tableData = ref([])
    const currentPage = ref(1) // 当前页码
    const pageSize = ref(5)    // 每页显示的行数
    const totalPages = ref(0)
    const totalRecords = ref()

    // 使用axios获取后端会员表总条目（封装在函数中）
    const getTotalRecords = () => {
      // 请设定后端的访问路径，不使用模拟数据
		get_total_records().then(res => {
        // res应为 { "length": 100 }
		console.log("查询结果", res);
        totalRecords.value = res.data.data;
        console.log("总条目", totalRecords.value);
        
        totalPages.value = Math.ceil(totalRecords.value / pageSize.value);
        console.log(totalPages.value);
        
      }).catch(err => {
        console.log(err);
      });
    }

// 完成handlePageChange 思路：未进行页数选择的时候默认显示第一页（也进行一次查询）；进行页数选择后将待查询页数与每页显示的行数发送给后端，并获取后端返回的查询结果并显示
const handlePageChange = (page) => {
	currentPage.value = page;
	handle_page_change(page, pageSize.value).then(res => {
		tableData.value = res.data.data;
		
		/******
		 *  res 数据结构
		 *  res = [{"id" : 1, 
		 *  "name" : "张三", 
		 *  "phone" : "12345678901", 
		 *  "gender" : "男", 
		 *  "cards" : ["涂鸦体验卡","金卡"], 
		 *  "startTime" : "2021-01-01", 
		 *  "notes" : "无"}]
		 */
	}).catch(err => {
		console.log(err);
	});
}


// 添加会员抽屉
const addDrawer = ref(false)
const closeDrawer = (val) => {
	addDrawer.value = val;
}

// 编辑会员信息
const EditDialogVisible = ref(false)
const editIndex = ref(0)
// 定义一个响应式变量，存放编辑会员信息
const editUser = ref({
	id: 0,
	name: '',
	phone: '',
	sex: '',
	birthday: '',
	note: ''
})

// 编辑会员信息发送至后端
const handleEdit = () => {
	editUser.value.id = tableData.value[editIndex.value].id
	console.log(editUser.value);
	console.log(tableData.value[editIndex.value]);
	
	handle_edit(editUser.value).then(res => {
		console.log(res);
		EditDialogVisible.value = false;
		if (!isContainerVisible.value) {
			console.log("关闭查询界面", isContainerVisible);
			isContainerVisible.value = !isContainerVisible.value;
		}
		handlePageChange(currentPage.value);
	}).catch(err => {
		console.log(err);
	});
}

// 注销会员
const delIndex = ref(0)
const handleDel = () => {
	const id = tableData.value[delIndex.value].id;
	handle_del(id).then(res => {
		console.log(res);
		handlePageChange(currentPage.value);
	}).catch(err => {
		console.log(err);
	});
}

// 查询会员信息
const viewIndex = ref(0)
const handleView = () => {
	console.log(isContainerVisible.value);
	const id = tableData.value[viewIndex.value].id;
	handle_view(id).then(res => {
	console.log(res.data.data);
	user.value = res.data.data;
	console.log(user.value);
	})
}
const user = ref({
	id: 0,
	name: '',
	phone: '',
	gender: '',
	birth: '',
	note: ''
})

// 设置el-container的显示参数，默认为true
const isContainerVisible = ref(true)

// 定义一个响应式变量，存放某一会员的会员卡信息
const userCard = ref([
])
/*****
 * userCard = [{
 * 	id: 0,
 *  name: '',
 *  type: '',
 *  totalCount: 0,
 *  endTime: '',
 *  status: ''// 0: 停用，1: 激活(视数据库规则而定)
 * }]
 */

// 发送请求到后端，查询某一会员的会员卡信息
const getUserCards = () => {
	const id = tableData.value[viewIndex.value].id;
	get_user_cards(id).then(res => {
		const processedData = res.data.data.map(row => ({ ...row, status: String(row.status) }));
    	userCard.value = processedData;
	}).catch(err => {
		console.log(err);
	});
}

// 定义activeTabName
const activeTabName = ref('tab1')

// @tab-click函数
const handleTabClick = () => {
	console.log(activeTabName.value);
	if (activeTabName.value === 'tab1') {
		getUserCards()
	} else if (activeTabName.value === 'tab2') {
		getResRecords()
	} else if (activeTabName.value === 'tab3') {
		getClassRecords()
	} else {
		getConsumeRecords()
	}
}

// statusIndex
const statusIndex = ref(0)
// switch 方法
const handleStatusChange = (index) => {
	console.log(index);
	const id = userCard.value[index].id;
	handle_status_change(id).then(res => {
		console.log(res.data.data.status);
		userCard.value[index].status = String(res.data.data);
	}).catch(err => {
		console.log(err);
	});
}

// resRecord存放预约记录
const resRecord = ref([
	/*****
	 * resRecord = [{
	 * 	courseName: '',
	 *  reserveTime: '',
	 *  cardName: '',
	 *  reservePeople: 0,
	 *  modifyTime: '',
	 *  useTime: '',
	 *  modifyUser: '',
	 *  note: '',
	 *  reserveType: ''
	 * }]
	 */
])

// 查询预约记录
const getResRecords = () => {
	console.log(user.value.id)
	const id = user.value.id
	get_res_records(id).then(res => {
		resRecord.value = res.data.data
	}).catch(err => {
		console.log(err);
	});
}

// 上课记录
const classRecord = ref([
	/****
	 *  classRecord = [{
	 * 	courseName: '',
	 *  classTime: '',
	 *  teacher: '',
	 *  userCard: '',
	 * 	coursePeople: 0,
	 *  useTime: 0,
	 *  teacherNote: '',
	 *  status: ''
	 * }]
	 */
])

// 查询上课记录
const getClassRecords = () => {
	console.log(user.value.id);
	const id = user.value.id
	get_class_records(id).then(res => {
		classRecord.value = res.data.data
	}).catch(err => {
		console.log(err);
	});
}

// 消费记录
const consumeRecord = ref([
	/****
	 *  consumeRecord = [{
	 * 	courseName: '',
	 *  consumeTime: '',
	 *  userCard: '',
	 *  consumePeople: 0,
	 *  useTime: 0,
	 *  note: '',
	 *  status: ''
	 * }]
	 */
])

// 查询消费记录
const getConsumeRecords = () => {
	console.log(user.value.id);
	const id = user.value.id
	get_consume_records(id).then(res => {
		consumeRecord.value = res.data.data
	}).catch(err => {
		console.log(err);
	});
}

// 初始化时加载所有数据
onMounted(() => {
	getTotalRecords();
	handlePageChange(currentPage.value);
});
</script>

<template>
	<el-container direction="vertical" v-show="isContainerVisible">
		<div>
			<el-button type="primary" icon="Plus" @click="addDrawer = true">添加会员</el-button>
			<el-button type="primary" icon="Upload">批量导入会员</el-button>
			<el-button type="primary" icon="Upload">批量绑卡</el-button>
		</div>
		<hr>

		<!-- <div>
			<span style="font-size: 14px; color: #606266">搜索：</span><el-input v-model="input" placeholder="请输入搜索内容"
				style="width: 200px;" @input="handleSearchInput"></el-input>
		</div> -->

		<div>
			<el-table :data="tableData" stripe border style="width: 100%">
				<el-table-column prop="name" label="会员姓名" />
				<el-table-column prop="phone" label="手机号" />
				<el-table-column prop="gender" label="性别" />
				<el-table-column prop="cards" label="会员卡" width="280" />
				<el-table-column prop="startTime" label="入会日期" />
				<el-table-column prop="note" label="备注" />
				<!-- 操作列 -->
				<el-table-column fixed="right" prop="operation" label="操作" width="280">
					<template #default={$index}>
						<el-button type="primary" size="small" icon="Edit"
							@click="EditDialogVisible = true, editIndex = $index">编辑</el-button>
						<el-button type="info" size="small" icon="Tickets"
							@click="viewIndex = $index, isContainerVisible = !isContainerVisible, handleView(), getUserCards()">查看</el-button>
						<el-button type="danger" size="small" icon="CloseBold"
							@click="delIndex = $index, handleDel()">注销</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<div>
			<el-pagination :page-size="pageSize" layout="prev, pager, next" :total="totalRecords"
				:current-page="currentPage" @current-change="handlePageChange" />
		</div>
	</el-container>

	<!-- 会员查看页面，默认显示状态为!isContainerVisible -->
	<el-container direction="vertical" v-show="!isContainerVisible">
		<el-header height="200px" style="margin-top: 20px; border:#ccc 1px solid; padding-top: 10px;">
			<el-row>
				<el-col :span="4">
					<!-- 此div用于显示头像 -->
					<div style="padding-top: 20px;">
						<el-avatar :size="100" :src="circleUrl" />
					</div>
				</el-col>
				<el-col :span="16">
					<!-- 此div用于显示会员信息 -->
					<el-text>
						<p>会员姓名：{{user.name}}</p>
						<p>手机号：{{user.phone}}</p>
						<p>性别：{{user.gender}}</p>
						<p>入会日期：{{user.birth}}</p>
						<p>备注：{{user.note}}</p>
					</el-text>
				</el-col>
				<el-col :span="4">
					<!-- 此div用于存放按钮“编辑信息”和“返回” -->
					<div style="display: flex; flex-direction: column; gap: 8px; align-items: center;">
						<!-- 编辑信息按钮 -->
						<el-button type="primary"
							@click="isContainerVisible = !isContainerVisible, handlePageChange(1);">返回</el-button>
						<el-button type="primary" @click="EditDialogVisible = true">编辑信息</el-button>
					</div>
				</el-col>
			</el-row>
		</el-header>
		<el-main style="padding-left: 0%; padding-right: 0%;">
			<el-tabs type="border-card" v-model="activeTabName" @click="handleTabClick">
				<el-tab-pane label="会员卡信息" name="tab1">
					<el-table :data="userCard" stripe border style="width: 100%">
						<el-table-column prop="cardName" label="会员卡" />
						<el-table-column prop="type" label="卡类型" />
						<el-table-column prop="validCount" label="可用次数" />
						<el-table-column prop="endTime" label="到期时间" width="280" />
						<el-table-column label="停用/激活">
							<template #default={$index}>
								<el-switch v-model="userCard[$index].status" active-value="0" inactive-value="1"
									style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
									active-text="激活" inactive-text="停用"
									@change="statusIndex = $index, handleStatusChange(statusIndex)" />
							</template>
						</el-table-column>
						<!-- 操作列 -->
						<el-table-column fixed="right" label="操作" width="280">
							<template #default={$index}>
								<el-button type="primary" size="small" @click=""
									:disabled="userCard[$index].status === '1'">充值</el-button>
								<el-button type="primary" size="small" @click=""
									:disabled="userCard[$index].status === '1'">扣费</el-button>
								<el-button type="danger" size="small" @click="">操作记录</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="预约记录" name="tab2">
					<el-table :data="resRecord" stripe border style="width: 100%">
						<el-table-column prop="name" label="课程" />
						<el-table-column prop="reserveTime" label="预约时间" />
						<el-table-column prop="cardName" label="会员卡" />
						<el-table-column prop="reserveNums" label="预约人数" />
						<el-table-column prop="totalCost" label="使用次数" />
						<el-table-column prop="lastModifyTime" label="操作时间" />
						<el-table-column prop="operator" label="操作人" />
						<el-table-column prop="note" label="我的备注" />
						<el-table-column prop="status" label="预约类型" />
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="上课记录" name="tab3">
					<el-table :data="classRecord" stripe border style="width: 100%">
						<el-table-column prop="courseName" label="课程" />
						<el-table-column prop="classTime" label="上课时间" />
						<el-table-column prop="teacherName" label="授课老师" />
						<el-table-column prop="cardName" label="会员卡" />
						<el-table-column prop="nums" label="上课人数" />
						<el-table-column prop="cost" label="使用次数" />
						<el-table-column prop="comment" label="老师评价" />
						<el-table-column prop="checkStatus" label="确认状态" />
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="消费记录" name="tab4">
					<el-table :data="consumeRecord" stripe border style="width: 100%">
						<el-table-column prop="courseName" label="课程" />
						<el-table-column prop="classTime" label="上课时间" />
						<el-table-column prop="teacher" label="授课老师" />
						<el-table-column prop="userCard" label="会员卡" />
						<el-table-column prop="coursePeople" label="上课人数" />
						<el-table-column prop="UseTime" label="使用次数" />
						<el-table-column prop="teacherNote" label="老师评价" />
						<el-table-column prop="status" label="确认状态" />
					</el-table>
				</el-tab-pane>
			</el-tabs>
		</el-main>
	</el-container>

	<!-- 添加会员抽屉 -->
	<el-drawer v-model="addDrawer" :direction="'rtl'" :size="'50%'" :before-close="handleClose" :show-close="false"
		:destroy-on-close="true">
		<AddUser :close-drawer="closeDrawer" :handle-page-change="handlePageChange" />
	</el-drawer>

	<!-- 会员编辑弹出框 -->
	<el-dialog v-model="EditDialogVisible" title="编辑会员信息" width="800" center align-center destroy-on-close>
		<template #default>
			<!-- 表单元素 -->
			<el-form label-width="80px">
				<el-form-item label="会员姓名">
					<el-input v-model="editUser.name"></el-input>
				</el-form-item>
				<el-form-item label="手机号">
					<el-input v-model="editUser.phone"></el-input>
				</el-form-item>
				<el-form-item label="性别">
					<el-radio-group v-model="editUser.sex">
						<el-radio label="男">男</el-radio>
						<el-radio label="女">女</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="出生日期">
					<el-date-picker v-model="editUser.birthday" type="date" placeholder="选择日期" />
				</el-form-item>
				<el-form-item label="备注">
					<el-input type="textarea" :rows="4" v-model="editUser.note"></el-input>
				</el-form-item>
			</el-form>
		</template>

		<template #footer>
			<div class="dialog-footer">
				<el-button @click="EditDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="handleEdit()">
					保存
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<style scoped>
.el-button {
	margin-right: 10px;
}

.el-table {
	margin-top: 20px;
}

.el-table .cell {
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.el-table th {
	background-color: #f5f5f5;
}

.el-table td {
	background-color: #fff;
}

.el-table thead th {
	color: #333;
	font-weight: bold;
}

.el-table .el-button {
	margin-right: 5px;
	display: inline-flex;
	align-items: center;
	justify-content: center;
}

.el-table .el-button--primary {
	background-color: #409EFF;
	border-color: #409EFF;
}

.el-table .el-button--primary:hover {
	background-color: #66b1ff;
	border-color: #66b1ff;
}

.el-table .el-button--info {
	background-color: #909399;
	border-color: #909399;
}

.el-table .el-button--info:hover {
	background-color: #bfbfc7;
	border-color: #bfbfc7;
}

.el-table .el-button--danger {
	background-color: #F56C6C;
	border-color: #F56C6C;
}

.el-table .el-button--danger:hover {
	background-color: #f78989;
	border-color: #f78989;
}
</style>